#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <functional>
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
#include "LockGuard.hpp"

using task_t = std::function<void()>;
class MessageRoute
{
private:
    bool IsExist(InetAddr who)
    {
        for (auto it = _online_users.begin(); it != _online_users.end(); ++it)
        {
            if (*it == who)
            {
                return true;
            }
        }
        return false;
    }

public:
    MessageRoute()
    {
        pthread_mutex_init(&_mutex, nullptr);
    }
    ~MessageRoute()
    {
        pthread_mutex_destroy(&_mutex);
    }
    void AddUser(InetAddr who)
    {
        LockGuard mutex(_mutex);
        // 如果用户第一次发送消息，将用户添加到在线用户中
        if (!IsExist(who))
            _online_users.push_back(who);
    }
    void DelUser(InetAddr who)
    {
        LockGuard mutex(_mutex);
        for (auto it = _online_users.begin(); it != _online_users.end(); ++it)
        {
            if (*it == who)
            {
                _online_users.erase(it);
                break;
            }
        }
    }

    // 进行消息转发(参数：who通过sockfd发送message) 将来线程会执行该函数
    void RouteHelper(int sockfd, std::string message, InetAddr who)
    {
        LockGuard mutex(_mutex);
        for (auto u : _online_users)
        {
            std::string send_message = "\n[" + who.Ip() + ":" + std::to_string(who.Port()) + "]# " + message + "\n";
          
            struct sockaddr_in peer = u.Addr();
            // 进行消息转发
            ::sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&peer, sizeof(peer));
        }
    }
    void Route(int sockfd, std::string message, InetAddr who)
    {
        // 1.用户首次发送消息时需要将自己添加到用户列表中
        AddUser(who);

        // 1.1如果用户要退出
        if (message == "Q" || message == "QUIT")
        {
            DelUser(who);
        }

        // 2.将消息转发任务投入线程池 让线程完成
        task_t task = std::bind(&MessageRoute::RouteHelper, this, sockfd, message, who);
        ThreadPool<task_t>::GetInstance()->push(task);
    }

private:
    std::vector<InetAddr> _online_users; // 所有的在线用户列表
    // 多线程可能同时访问_online_users,需要加锁
    pthread_mutex_t _mutex;
};